package cn.frh.Exception;

import cn.frh.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalException {
    @ExceptionHandler(value = Exception.class)
    public JSONResult customException(Exception e){
        e.printStackTrace();
        log.error("全局的异常捕捉-customException方法，发生异常，异常信息为：{}", e.getMessage());
        return JSONResult.error(GlobalExceptionCode.ERROR);
    }

    @ExceptionHandler(value = GlobalCustomException.class)
    public JSONResult customException(GlobalCustomException e){
        return JSONResult.error(e);
    }
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult customException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer buffer = new StringBuffer();
        allErrors.forEach(obj->{
            buffer.append(" -- ").append(obj.getDefaultMessage()).append(" -- ");
        });
        return JSONResult.error(buffer.toString(), "1000");
    }

}
